import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sleep/help_style.dart';
import 'package:sleep/model/setting/setting.dart';
import 'package:sleep/provider/db_provider.dart';

enum SettingType {
  sleep,
  fatuige,
}

class Setting extends ConsumerWidget {
  final SettingType type;
  const Setting({Key? key, required this.type}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Setting",
          style: HelpStyle.titleStyle,
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            if (type == SettingType.sleep) widget(sleep(ref), 'Sleep'),
            if (type == SettingType.fatuige) widget(fatigue(ref), 'Fatigue'),
            widget(pluse(ref), 'Pluse'),
          ],
        ),
      ),
    );
  }

  Widget widget(List<_UserInputModel> models, String title) {
    return Container(
      decoration: HelpStyle.decoration,
      margin: EdgeInsets.all(HelpStyle.cellMargin),
      padding: EdgeInsets.all(HelpStyle.cellMargin),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(
          title,
          style: HelpStyle.contextStyle.copyWith(color: HelpStyle.primarycolor),
        ),
        ...models.map((e) => input(e)).toList()
      ]),
    );
  }

  List<_UserInputModel> pluse(WidgetRef ref) {
    final db = ref.read(dbProvider);
    final map = db.pluseSetting().toJson();
    return mapToModels(map, (value, key) {
      final oldV = map[key];
      if (oldV == value) return;
      map[key] = value;
      db.saveSetting(
          pluse: PluseSetting.fromJson(map),
          needNotify: key == 'Multiple' ? true : false);
    });
  }

  List<_UserInputModel> sleep(WidgetRef ref) {
    final db = ref.read(dbProvider);
    final map = db.sleepSetting().toJson();
    // return mapToModels(map, (value, key) {
    //   final oldV = map[key];
    //   if (oldV == value) return;
    //   map[key] = value;
    //   db.saveSetting(sleep: SleepSetting.fromJson(map));
    // });

    List<_UserInputModel> models = [];
    final titleMap = SleepSetting.title();
    for (final key in titleMap.keys) {
      _UserInputModel model = _UserInputModel(
          defaultValue: map[key],
          title: titleMap[key] ?? key,
          key: key,
          change: (double value) {
            final oldV = map[key];
            if (oldV == value) return;
            map[key] = value;
            db.saveSetting(
                sleep: SleepSetting.fromJson(map),
                needNotify: key == 'multiple' ? true : false);
          });
      models.add(model);
    }
    return models;
  }

  List<_UserInputModel> fatigue(WidgetRef ref) {
    final db = ref.read(dbProvider);
    final map = db.fatuigeSetting().toJson();
    final titleMap = FatigueSetting.title();
    List<_UserInputModel> models = [];
    for (final key in titleMap.keys) {
      _UserInputModel model = _UserInputModel(
          defaultValue: map[key],
          title: titleMap[key] ?? key,
          key: key,
          change: (double value) {
            final oldV = map[key];
            if (oldV == value) return;
            map[key] = value;
            db.saveSetting(
                fatuige: FatigueSetting.fromJson(map),
                needNotify: key == 'multiple' ? true : false);
          });
      models.add(model);
    }
    return models;
  }

  List<_UserInputModel> mapToModels(
      Map<String, dynamic> map, Function(double, String) change) {
    List<_UserInputModel> models = [];
    for (final key in map.keys) {
      _UserInputModel model = _UserInputModel(
          defaultValue: map[key],
          title: key,
          key: key,
          change: (double value) {
            change(value, key);
          });
      models.add(model);
    }
    return models;
  }

  Widget input(_UserInputModel model) {
    return Container(
      margin: EdgeInsets.only(left: 8, right: 18, top: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(model.title, style: HelpStyle.contextStyle),
          const SizedBox(height: 6),
          TextField(
              onChanged: ((value) {
                final doubleValue = double.tryParse(value);
                model.change(doubleValue ?? model.defaultValue);
              }),
              controller:
                  TextEditingController(text: model.defaultValue.toString()),
              style: HelpStyle.titleStyle,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                fillColor: HelpStyle.backgroundColor,
                labelStyle: MaterialStateTextStyle.resolveWith(
                    (states) => HelpStyle.titleStyle),
                filled: true,
                isCollapsed: true,
                border: const OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(25))),
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
              )),
        ],
      ),
    );
  }
}

class _UserInputModel {
  final String title;
  final double defaultValue;
  final String key;
  ValueChanged<double> change;
  _UserInputModel({
    required this.defaultValue,
    required this.title,
    required this.key,
    required this.change,
  });
}
